package com.puccampinas.finalproject.rest;

import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.StringUtils;

import com.eaio.uuid.UUID;
import com.google.gson.Gson;
import com.puccampinas.finalproject.core.controller.UserController;
import com.puccampinas.finalproject.core.logs.LogUtils;
import com.puccampinas.finalproject.core.logs.LoggerType;
import com.puccampinas.finalproject.core.persistence.entity.User;
import com.puccampinas.finalproject.core.util.HttpUtil;
import com.puccampinas.finalproject.rest.to.RequestResponse;
import com.puccampinas.finalproject.rest.to.ResponseStatus;

@Path("/api")
public class RequestHandler {

	@GET
    @Path("ping")
    @Produces({MediaType.APPLICATION_XML})
    public RequestResponse ping(@Context HttpServletRequest request) {

    	LogUtils.info(LoggerType.REQUESTS_ANSWERED, "Requested. | URL=" + request.getRequestURL() + (request.getQueryString() == null ? "" : "?" + request.getQueryString()));
    	
        String ticket = new UUID().toString();

        RequestResponse requestResponse = new RequestResponse();
        
        requestResponse.setDate(new Date());
        requestResponse.setTicket(ticket);
        requestResponse.setStatus(ResponseStatus.OK);

        LogUtils.info(LoggerType.REQUESTS_ANSWERED, "Answered. | URL=" + request.getRequestURL() + (request.getQueryString() == null ? "" : "?" + request.getQueryString()) + " | ANSWER=" + requestResponse.toString());
        
        return requestResponse;
    }

	@GET
    @Path("canLogin/")
    @Produces({MediaType.APPLICATION_JSON})
	public String verifyLogin(@QueryParam("usuario") String usuario, @QueryParam("password") String password, @QueryParam("callback") String callback) {
		
		String ticket = new UUID().toString();
		
		RequestResponse rp = new RequestResponse();
		rp.setTicket(ticket);
		rp.setStatus(ResponseStatus.INVALID_PARAMETERS);
		rp.setMessage("Parametros invalidos");
		User user = null;
		
		if (StringUtils.isNotEmpty(usuario) && StringUtils.isNotEmpty(password)) {
			String result;
			try {
				String url = "http://tcc.renanwilliam.com/webservice.php?action=login&email=$email$&pass=$pass$";
				url = url.replace("$email$", URLEncoder.encode(usuario,"ISO-8859-1"));
				url = url.replace("$pass$", URLEncoder.encode(password, "ISO-8859-1"));
				result = HttpUtil.getResponse(url);
				
				if (result.toLowerCase().contains("<result>true</result>")) {
					user = UserController.find(usuario);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} 
		
		Gson gson = new Gson();
		String json = gson.toJson(user);
		
		return callback + "(" + json + ")";
	}
	
}
